﻿using Common.Logging;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Xmart.Action
{
    public abstract
        class AbstractAction : IAction
    {
        #region 构造

        public AbstractAction(ISessionFactory sessionFactory)
        {
            SessionFactory = sessionFactory;
        }

        #endregion

        #region 字段

        /// <summary>
        /// 通用模版
        /// </summary>

        ILog log = LogManager.GetCurrentClassLogger();
        #endregion

        #region 属性

        /// <summary>
        /// SessionFactory
        /// </summary>
        public virtual ISessionFactory SessionFactory { get; set; }

        #endregion

        #region 方法

        public virtual IActionResult Execute(string name, params object[] args)
        {
            log.DebugFormat("Execute:{0},Args{1}", name, args);
            try
            {
                var mi = FindMethod(name, args);

                log.DebugFormat("FindMethod:{0}", mi);

                return mi.Invoke(this, args) as IActionResult;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error:{0}", ex, name);
            }

            return null;
        }

        private System.Reflection.MethodInfo FindMethod(string key, object[] args)
        {
            Type[] typeArgs = Type.EmptyTypes;

            if (args != null && args.Length > 0)
            {
                typeArgs = (from p in args where p != null select p.GetType()).ToArray();
            }

            var info = Spring.Util.ReflectionUtils.GetGenericMethod(this.GetType(), key, null, typeArgs);
            if (info == null)
                info = Spring.Util.ReflectionUtils.GetMethod(GetType(), key, typeArgs);
            return info;
        }

        #endregion
    }
}
